package com.share.payment.service.impl;

import com.alibaba.fastjson2.JSON;
import com.share.common.core.context.SecurityContextHolder;
import com.share.common.core.domain.R;
import com.share.common.core.exception.ServiceException;

//import com.share.payment.config.WxPayV3Properties;
import com.share.payment.domian.CreateWxPaymentForm;
import com.share.payment.domian.PaymentInfo;
import com.share.payment.domian.WxPrepayVo;
import com.share.payment.service.IPaymentInfoService;
import com.share.payment.service.IWxPayService;
import com.share.payment.utils.RequestUtils;
import com.share.user.api.RemoteUserService;
import com.share.user.domain.UserInfo;
import com.wechat.pay.java.core.notification.NotificationParser;
import com.wechat.pay.java.core.notification.RequestParam;
import com.wechat.pay.java.service.payments.model.Transaction;
import com.wechat.pay.java.service.payments.jsapi.JsapiServiceExtension;
import com.wechat.pay.java.service.payments.jsapi.model.*;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.math.BigDecimal;

@Service
@Slf4j
public class WxPayServiceImpl implements IWxPayService {


    @Autowired
    IPaymentInfoService paymentInfoService;

//    @Autowired
//    RSAAutoCertificateConfig rsaAutoCertificateConfig;

//    @Autowired
//    WxPayV3Properties wxPayV3Properties;

    @Autowired
    RemoteUserService remoteUserService;

    /**
     * 创建微信支付订单
     *
     * @param createWxPaymentForm
     * @return
     */
//    @Override
//    public WxPrepayVo createWxPayment(CreateWxPaymentForm createWxPaymentForm) {
//        //1 添加微信支付记录（状态：未支付）
//        PaymentInfo paymentInfo = paymentInfoService.savePaymentInfo(createWxPaymentForm.getOrderNo());
//
//        //2 创建微信封装对象 JsapiServiceExtension
//        JsapiServiceExtension service = new JsapiServiceExtension.Builder().config(rsaAutoCertificateConfig).build();
//
//        //3 封装这个对象需要的相关参数
//        // request.setXxx(val)设置所需参数，具体参数可见Request定义
//        PrepayRequest request = new PrepayRequest();
//        Amount amount = new Amount();
//        //为了测试设置0.01元
//        amount.setTotal(1);
//        amount.setTotal(paymentInfo.getAmount().multiply(new BigDecimal(100)).intValue());
//        request.setAmount(amount);
//
//        request.setAppid(wxPayV3Properties.getAppid());
//        request.setMchid(wxPayV3Properties.getMerchantId());
//        request.setDescription(paymentInfo.getContent());
//        request.setNotifyUrl(wxPayV3Properties.getNotifyUrl());
//        request.setOutTradeNo(paymentInfo.getOrderNo());
//
//        //获取用户信息
//        Payer payer = new Payer();
//        //远程调用
//        R<UserInfo> userInfoR = remoteUserService.getInfo(SecurityContextHolder.getUserId());
//        UserInfo userInfo = userInfoR.getData();
//        if (userInfo == null) {
//            throw new ServiceException("用户不存在");
//        }
//
//        String openid = userInfo.getWxOpenId();
//        payer.setOpenid(openid);
//        request.setPayer(payer);
//
//        //4 调用第二步创建对象里面的方法，生成预支付订单
//        PrepayWithRequestPaymentResponse response = service.prepayWithRequestPayment(request);
//
//        //5 按照要求返回需要的数据WxPrepayVo
//        WxPrepayVo wxPrepayVo = new WxPrepayVo();
//        BeanUtils.copyProperties(response, wxPrepayVo);
//        wxPrepayVo.setTimeStamp(response.getTimeStamp());
//
//        return wxPrepayVo;
//    }

    @Override
    public WxPrepayVo createWxPayment(CreateWxPaymentForm createWxPaymentForm) {
        //1 添加微信支付记录（状态：未支付）
        PaymentInfo paymentInfo = paymentInfoService.savePaymentInfo(createWxPaymentForm.getOrderNo());
        WxPrepayVo wxPrepayVo = new WxPrepayVo();
        // 为每个字段设置假数据
        wxPrepayVo.setAppId("fakeAppId");
        wxPrepayVo.setTimeStamp("123456");
        wxPrepayVo.setNonceStr("fakeNonceStr");
        wxPrepayVo.setPackageVal("prepay_id=fakeValue");
        wxPrepayVo.setSignType("MD5");
        wxPrepayVo.setPaySign("fakeSign");
        return wxPrepayVo;
    }

    /**
     * 微信支付异步通知接口
     *
     * @param request
     */
//    @Override
//    public void wxnotify(HttpServletRequest request) {
//        String wechatPaySerial = request.getHeader("Wechatpay-Serial");
//        String nonce = request.getHeader("Wechatpay-Nonce");
//        String timestamp = request.getHeader("Wechatpay-Timestamp");
//        String signature = request.getHeader("Wechatpay-Signature");
//        String requestBody = RequestUtils.readData(request);
//
//
//        //2.构造 RequestParam
//        RequestParam requestParam = new RequestParam.Builder()
//                .serialNumber(wechatPaySerial)
//                .nonce(nonce)
//                .signature(signature)
//                .timestamp(timestamp)
//                .body(requestBody)
//                .build();
//
//
//        //3.初始化 NotificationParser
//        NotificationParser parser = new NotificationParser();
//        //4.以支付通知回调为例，验签、解密并转换成 Transaction
//        Transaction transaction = parser.parse(requestParam, Transaction.class);
//        log.info("成功解析：{}", JSON.toJSONString(transaction));
//        if (null != transaction && transaction.getTradeState() == Transaction.TradeStateEnum.SUCCESS) {
//            //5.处理支付业务
//            paymentInfoService.updatePaymentStatus(transaction);
//        }
//    }


    /**
     * 支付状态查询
     *
     * @param orderNo
     * @return
     */
//    @Override
//    public  Transaction queryPayStatus(String orderNo) {
//        // 构建service
//        JsapiServiceExtension service = new JsapiServiceExtension.Builder().config(rsaAutoCertificateConfig).build();
//
//        QueryOrderByOutTradeNoRequest queryRequest = new QueryOrderByOutTradeNoRequest();
//        queryRequest.setMchid(wxPayV3Properties.getMerchantId());
//        queryRequest.setOutTradeNo(orderNo);
//        Transaction transaction = service.queryOrderByOutTradeNo(queryRequest);
//        return transaction;
//    }


}